package top.ezzz.common;

import com.baomidou.mybatisplus.solon.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Result;

import java.util.LinkedHashMap;

@Slf4j
public class R extends LinkedHashMap<String, Object> {

    // 返回参数
    private static String CODE = "code";
    private static String MESSAGE = "message";
    private static String DATA = "data";
    //分页参数
    private static String TOTAL = "total";
    private static String PAGE = "page";
    private static String SIZE = "size";
    //其他参数
    private static String SUCCESS = "success";


    public static R create() {
        return new R();
    }

    public R set(String key, Object value) {
        put(key, value);
        return this;
    }


    public static R ok(Object data) {
        R result = R.create();
        if (data instanceof Page) {
            Page page = (Page) data;
            result = result.set(DATA, page.getRecords())
                    .set(SUCCESS, true)
                    .set(CODE, 0)
                    .set(MESSAGE, "操作成功")
                    .set(TOTAL, page.getTotal())
                    .set(PAGE, page.getCurrent())
                    .set(SIZE, page.getSize());
        } else if (data instanceof Result) {
            Result resultSolon = (Result) data;
            result = result.set(DATA, resultSolon.getData())
                    .set(SUCCESS, resultSolon.getCode() == Result.SUCCEED_CODE)
                    .set(CODE, resultSolon.getCode())
                    .set(MESSAGE, resultSolon.getDescription());
        } else {
            result = result.set(DATA, data)
                    .set(SUCCESS, true)
                    .set(CODE, 0)
                    .set(MESSAGE, "操作成功");
        }
        log.info("请求路径：{}", Context.current().path());
        log.info("返回参数：{}", result);
        return result;
    }

    public static R error(String message) {
        R result = R.create()
                .set(SUCCESS, false)
                .set(CODE, 500)
                .set(MESSAGE, message);
        log.info("请求路径：{}", Context.current().path());
        log.info("返回参数：{}", result);
        return result;
    }

    public static R error(int code, String message) {
        R result = R.create()
                .set(SUCCESS, false)
                .set(CODE, code)
                .set(MESSAGE, message);
        log.info("请求路径：{}", Context.current().path());
        log.info("返回参数：{}", result);
        return result;
    }


}
